<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="3" :sm="6">
            <a-form-item label="车主名称">
              <a-input placeholder="请输入车主名称" v-model="queryParam.userName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="6">
            <a-form-item label="手机号">
              <a-input placeholder="请输入手机号" v-model="queryParam.mobile"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="6">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col v-has="'parkUser:add'" :md="3" :sm="6">
            <a-form-item label="车位编号">
              <a-input placeholder="请输入车位编号" v-model="queryParam.parkNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col v-has="'parkUser:add'" :md="3" :sm="6">
            <a-form-item label="区域名称">
              <a-select placeholder="请选择区域" v-model="queryParam.areaId" :options="areaIdOptions"></a-select>
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="6">
            <a-form-item label="过期时间">
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="6">
            <a-form-item label="过期时间">
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button style="margin-right: 6px" type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button v-has="'parkUser:add'" @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('月租车信息')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择<a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange"
          :scroll="{ x: 1400}"
          style="word-break: break-all"
      >

        <span slot="action" slot-scope="text, record">
          <a v-has="'parkUser:add'" @click="bindPlantNo(record)">绑定车牌号</a>
          <a-divider v-has="'parkUser:add'" type="vertical"/>
          <a v-show="record.startTime" @click="handleDelay(record)">延期</a>
          <a-divider v-show="record.startTime" type="vertical"></a-divider>
          <a @click="handleDetail(record)">详情</a>
           <a-divider type="vertical"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>
    <parking-space-edit-modal ref="editModalForm" @ok="modalFormOk"></parking-space-edit-modal>
    <parking-s-pace-add-modal ref="addModalForm" @ok="modalFormOk"></parking-s-pace-add-modal>
    <parking-space-delay-modal ref="delayModalForm" @ok="modalFormOk"></parking-space-delay-modal>
  </a-card>
</template>

<script>
import ParkingSpaceEditModal from "./modules/ParkingSpaceEditModal"
import ParkingSPaceAddModal from './modules/ParkingSpaceAddModal'
import ParkingSpaceDelayModal from "./modules/ParkingSpaceDelayModal";
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile, postAction} from '@api/manage'
import {filterObj} from '@/utils/util';

export default {
  name: "ParkingSpace",
  mixins: [JeecgListMixin],
  components: {
    ParkingSpaceEditModal,
    ParkingSPaceAddModal,
    ParkingSpaceDelayModal
  },
  data() {
    return {

      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName',
          width: 150
        },
        {
          title: '所在区域',
          align: "center",
          dataIndex: 'areaName',
          width: 150
        },
        {
          title: '车位编号',
          align: "center",
          dataIndex: 'parkNumber',
          width: 150
        },
        {
          title: '车主名称',
          align: "center",
          dataIndex: 'userName',
          width: 120
        },
        {
          title: '车主电话',
          align: "center",
          dataIndex: 'mobile',
          width: 150
        },
        {
          title: '有效期开始时间',
          align: "center",
          dataIndex: 'startTime',
          width: 150
        },
        {
          title: '有效期结束时间',
          align: "center",
          dataIndex: 'endTime',
          width: 150
        },
        {
          title: '停车状态',
          align: 'center',
          dataIndex: 'parkStatus',
          width: 150,
          customRender: function (t, r, index) {
            if (t === 0 || t === "0") {
              return '无车辆停靠';
            }
            if (t === 1 || t === "1") {
              return "有车辆停靠";
            }
            return ""
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          width: 180,
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/parkCar/parkNumber/list",
        delete: "/parkCar/parkNumber/delete",
        deleteBatch: "/parkCar/parkNumber/removeByBatch",
        exportXlsUrl: "/parkCar/parkCarMonthly/ParkCarMonthlyExportXls",
        importExcelUrl: "/parkCar/parkCarMonthly/importExcel",
        carTypeList: "/ConfigCarType/configCarType/parkCarTypeList",
        getParkInfos: "/parking/parkInfo/parkInfoList",
        areaList: "/area/parkAreaInfo/getAreaInfos",
        synchronizeSpaceInfo: "/parkCar/parkNumber/synchronizeSpaceInfo"
      },
      queryParam: {
        "areaId": "",
        "endTime_begin": "",
        "endTime_end": "",
        "plateNo": "",
        "parkNumber": "",
        "parkCode": "",
        "carTypeId": "",
        "type": "-1",
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      CarTypeOptions: [{value: '', label: '请选择车辆类型'}],
      parkInfos: [{label: '请选择车场', value: ''}],
      areaIdOptions: [{label: '请选择区域', value: ""}]
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.keyupEnter()
  },
  mounted() {
    this.loadParkInfo()
    this.loadAreaList()
  },
  methods: {

    loadParkInfo() {
      const that = this
      getAction(this.url.getParkInfos).then((res) => {
        if (res.result) {
          that.parkInfos = [{label: '请选择车场', value: ''}]
          res.result.forEach(parkInfo => {
            that.parkInfos.push({
              label: parkInfo.parkName,
              value: parkInfo.parkCode
            })
          })
        }
      })
    },
    loadAreaList() {
      const that = this
      if (!this.url.areaList) {
        this.$message.error("请设置this.url.areaList属性!")
        return
      }
      this.loading = true
      let params = {}
      getAction(this.url.areaList, params).then(res => {
        if (res.success) {
          that.areaIdOptions = [{value: "", label: '请选择区域'}]
          res.result.forEach(area => {
            that.areaIdOptions.push({
              value: area.id,
              label: area.areaName
            })
          })
        } else {
          this.$message.error(res.message);
        }
        that.loading = false
      })
    },

    bindPlantNo(record) {
      this.$refs.editModalForm.edit(record)
      this.$refs.editModalForm.title = "绑定车牌";
      this.$refs.editModalForm.disableSubmit = false;
    },
    handleDelay(record) {
      this.$refs.delayModalForm.edit(record)
      this.$refs.delayModalForm.title = "车位延期";
      this.$refs.delayModalForm.disableSubmit = false;
    },
    handleAdd: function (record) {
      this.$refs.addModalForm.edit(record)
      this.$refs.addModalForm.title = "新增车位";
      this.$refs.addModalForm.disableSubmit = false;
    },

    daysBetween(sDate1, sDate2) {
      let time1 = Date.parse(new Date(sDate1).toDateString());
      let time2 = Date.parse(new Date(sDate2).toDateString());
      let nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
      return nDays;
    },
    synCloudSpace() {
      const that = this;
      postAction(this.url.synchronizeSpaceInfo).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
          that.onClearSelected();
        } else {
          this.$message.error(res.message);
        }
        that.loading = false
      })
    },

    handleExportXls(fileName) {

      let param = {...this.queryParam};
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
        param.plateNo = this.queryParam.plateNo;
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end === "") {
        this.$message.error("请选择结束时间")
        return
      }
      if (this.queryParam.endTime_begin === "" && this.queryParam.endTime_end !== "") {
        this.$message.error("请选择开始时间")
        return
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        if (this.queryParam.endTime_begin > this.queryParam.endTime_end) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {

        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.endTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.endTime_end = dateString;
    },

    loadData(arg) {
      const that = this
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams();
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records;
          that.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        that.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.endTime_begin;
      let endTime = this.queryParam.endTime_end;
      if (startTime !== "" && endTime !== "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.loadData(1);
    },
    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
      }
      return filterObj(param);
    },

    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {
              ids: ids
            }).then((res) => {
              if (res.success || res.code == 200) {
                that.$message.success(res.message || res.msg);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message || res.msg);
              }
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    keyupEnter() {
      // eslint-disable-next-line no-unused-vars
      document.onkeydown = e => {
      }
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
